/**
 * @name yun.js
 * @desc 纯js+css3+html5 UI插件
 * @author yunduansing
 * @version 0.0.5
 * @copyriht http://www.yunduansing.com/
 * @license Apache License version 2.0
 */
;
!
(function() {
	coreui = {
		version: "0.0.3",
		author: "yunduansing",
		copyright: "http://www.yunduansing.com",
		license: "Apache License version 2.0",
		/*表格插件*/
		grid: function(params) {
			var d = document;
			var columns, data;
			columns = params.columns; //表头列
			var table = d.getElementById(params.id);
			if(table.childElementCount > 0) {
				for(var i = 1; i < table.childElementCount; i++) {
					table.removeChild(table.children[i--]);
				}
				if(params.checkbox){
					d.getElementsByName(params.id + '-checkAll')[0].checked = false;
				}
			}else{
				table.setAttribute("class", "table");
				if(params.width){
					table.style.width=params.width;
				}
				if(params.height){
					table.style.height=params.height;
				}
				var tr = d.createElement("tr");
				//如果开启行号则添加行号列
				params.rownumber=params.rownumber?params.rownumber:true;
				if(params.rownumber) {
					var th = d.createElement("th");
					th.style.width="60px";
					tr.appendChild(th);
				}
				//如果开启复选框则添加复选框列
				if(params.checkbox) {
					var th = d.createElement("th");
					th.innerHTML = "<input type='checkbox' name='" + params.id + "-checkAll'/>";
					th.style.width="50px";
					var chAll = th.firstChild;
					coreui.on(chAll, "change", function() {
						var chItem = d.getElementsByName(params.id + "-checkSingle");
						if(chAll.checked) {
							for(var i = 0; i < chItem.length; i++) {
								chItem[i].checked = true;
							}
						} else {
							for(var i = 0; i < chItem.length; i++) {
								chItem[i].checked = false;
							}
						}
					});
					tr.appendChild(th);
				}
				for(var i = 0; i < columns.length; i++) {
					var th = d.createElement("th");
					th.innerHTML = columns[i].title;
					if(columns[i].hidden)
						th.style.display="none";
					tr.appendChild(th);
				}
				var thead = d.createElement("thead");
				thead.appendChild(tr);
				table.appendChild(thead);
			}
			if(typeof(params.obj) == "object") {
				var res = params.obj; //数据
				generate(res);
			} else { // 传递的是 url参数
				var search={};
				if(params.search){
					params.search.index=params.index;
					params.search.size=params.size;
					search=params.search;
				}else{
					search={"index":params.index,"size":params.size};
				}
				coreui.post(params.obj,search,function(res) {
					var rest = res; //数据
					generate(rest);
				});
			}
			//根据数据生成表格
			function generate(res) {
				var table = d.getElementById(params.id);
				var tbody = d.createElement("tbody");
				for(var j = 0; j < res.data.length; j++) {
					var tr = d.createElement("tr");
					//如果开启行号则添加行号列
					if(params.rownumber) {
						var td = d.createElement("td");
						td.innerHTML = j + 1;
						tr.appendChild(td);
					}
					//如果开启复选框则添加复选框列
					if(params.checkbox) {
						var td = d.createElement("td");
						td.innerHTML = "<input type='checkbox' value='"+res.data[j][params.key]+"' name='" + params.id + "-checkSingle'/>";
						tr.appendChild(td);
					}
					var keyValue;
					for(var i = 0; i < columns.length; i++) {
						var item = columns[i];
						if(item.type) {
							var td = d.createElement("td");
							td.innerHTML = item.formatter(keyValue);
							if(item.align){
								td.style.textAlign=item.align;
							}
							if(item.width){
								td.style.width=item.width;
							}
							if(item.height){
								td.style.height=item.height;
							}
							tr.appendChild(td);
						} else if(item.field) {
							var td = d.createElement("td");
							if(item.formatter) {
								var format = item.formatter;
								td.innerHTML = format(res.data[j][item.field]);
							} else {
								td.innerHTML = res.data[j][item.field];
							}
							if(item.hidden)
								td.style.display="none";
							if(item.align){
								td.style.textAlign=item.align;
							}
							if(item.width){
								td.style.width=item.width;
							}
							if(item.height){
								td.style.height=item.height;
							}
							tr.appendChild(td);
							if(params.key && params.key == item.field) {
								keyValue = res.data[j][params.key];
							}
						}
					}
					tbody.appendChild(tr);
				}
				table.appendChild(tbody);
				//分页
				if(typeof(params.size) != "undefined") {
					coreui.page({
						id: params.pager,
						size: params.size,
						rows: res.rows,
						jump: params.jump?params.jump:true,
						msg: params.msg?params.msg:true,
						index: res.index,
						pagesize: params.pagesize,
						onpaging: function(index, size) {
							params.index = index;
							if(size) params.size = size;
							coreui.grid(params);
						}
					});
				}
			}

			//DOM没有提供insertAfter()方法
			function insertAfter(newElement, targetElement) {
				var parent = targetElement.parentNode;
				if(parent.lastChild == targetElement) {
					// 如果最后的节点是目标元素，则直接添加。因为默认是最后
					parent.appendChild(newElement);
				} else {
					parent.insertBefore(newElement, targetElement.nextSibling);
					//如果不是，则插入在目标元素的下一个兄弟节点 的前面。也就是目标元素的后面
				}
			}
		},
		/*获取表格的已选择key*/
		getSelectIds:function(tableId){
			var chk = document.getElementsByName(tableId+"-checkSingle");
            var ids = [];
            for(var i=0;i<chk.length;i++){
            	if (chk[i].checked)
                    ids.push(chk[i].getAttribute("value"));
            }
            return ids;
		},
		/*ajax请求,默认async:true,get请求*/
		ajax: function(params) {
			if(typeof(params.async) == 'undefined')
				params.async = true; //设置默认异步方式
			if(typeof(params.dataType) == 'undefined')
				params.dataType = 'json'; //设置默认使用json方式
			var xmlhttp;
			if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari

				xmlhttp = new XMLHttpRequest();
			} else { // code for IE6, IE5

				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			xmlhttp.onreadystatechange = function() {
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					if(params.dataType == 'xml') {
						res = xmlhttp.responseXML;
						params.success(res);
					} else if(params.dataType == 'json') {
						res = JSON.parse(xmlhttp.responseText);
						params.success(res);
					} else {
						res = xmlhttp.responseText;
						params.success(res);
					}
				}
			}
			xmlhttp.open(params.method ? params.method : 'GET', params.url, params.async);
			if(params.method && params.method == 'post' && params.data) {
				xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlhttp.send(params.data);
			} else {
				xmlhttp.send();
			}
			if(!params.async) {
				res = xmlhttp.responseText;
				params.success(res);
			}
		},
		post:function(url,data,success){
			var xmlhttp;
			if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari

				xmlhttp = new XMLHttpRequest();
			} else { // code for IE6, IE5

				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			xmlhttp.onreadystatechange = function() {
				if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
					var res=JSON.parse(xmlhttp.responseText);
					success(res);
				}
			}
			xmlhttp.open("POST",url,true);
			xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			if(data instanceof Object){
				var str="";
				for(var i in data){
					if(data.hasOwnProperty(i)){
						if(str.length==0){
							str+=i+"="+data[i];
						}else{
							str+="&"+i+"="+data[i];
						}
					}
				}
				xmlhttp.send(str);
			}else{
				xmlhttp.send(data);
			}
		}
		,get:function(url,data,success){
			var xmlhttp;
			if(window.XMLHttpRequest){
				xmlhttp=new XMLHttpRequest();
			}else{
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			xmlhttp.onreadystatechange=function(){
				if(xmlhttp.readyState==4&&xmlhttp.status==200){
					success(xmlhttp.responseText);
				}
			}
			xmlhttp.open("GET",url,true);
			xmlhttp.send();
		}
		/*分页插件*/
		,page: function(params) {
			var d = document;
			var pager = d.getElementById(params.id);
			var size = params.size; //每页显示条数
			var count = params.rows; //总记录数
			var pagecount = Math.ceil(count / size); //总页数
			var pagecontainer = d.createElement("div");
			
			if(pagecount > 0) {
				//是否显示表格信息
				if(params.msg) {
					var div = d.createElement("div");
					div.setAttribute("class", "page-msg");
					var msg = "共" + params.rows + "条记录，当前第" + params.index + "页";
					msg += ",共" + pagecount + "页，每页";
					var text = d.createTextNode(msg);
					div.appendChild(text);
					var select = d.createElement("select");
					for(var i = 0; i < params.pagesize.length; i++) {
						var option = d.createElement("option");
						option.setAttribute("value", params.pagesize[i]);
						if(params.size == params.pagesize[i]) {
							option.setAttribute("selected", "selected");
						}
						var text = d.createTextNode(params.pagesize[i]);
						option.appendChild(text);
						select.appendChild(option);
					}
					coreui.on(select, 'change', function() {
						params.onpaging(1, select.value)
					});
					div.appendChild(select);
					pagecontainer.appendChild(div);
				}
				
				var ul = d.createElement("ul");
				ul.setAttribute("class", "page");
				var leftOrRight = 3; //活动页码左边或右边的页码数，此处决定是否显示（…）
				var showPage=7;

				var li1 = d.createElement("li");
				var a = "<a href='javascript:;'  data-index='1'>首页</a>";
				li1.setAttribute("data-index", params.index==1?0:1);
				li1.innerHTML = a;
				ul.appendChild(li1);
				var a = "<a href='javascript:;' data-index='" + (params.index - 1) + "'>上一页</a>";
				var li2 = d.createElement("li");
				li2.setAttribute("data-index", params.index==1?0:(params.index - 1));
				li2.innerHTML = a;
				ul.appendChild(li2);

				var startPageNo=1,endPageNo=pagecount;
				if(params.index-leftOrRight<=1){
					if(params.index+leftOrRight<=showPage&&showPage<=pagecount){
						endPageNo=showPage;
					}
				}else if(params.index+leftOrRight>=pagecount){
					if(pagecount-params.index-leftOrRight<=showPage&&pagecount-showPage>=1){
						startPageNo=pagecount-showPage;
					}
				}else{
					startPageNo=params.index-leftOrRight;
					endPageNo=params.index+leftOrRight;
				}
				if(startPageNo!=1){
					var li=d.createElement("li");
					var a = "<a href='javascript:;' class='disabled' data-index='0'>…</a>";
					li.setAttribute("data-index", 0);
					li.innerHTML=a;
					ul.appendChild(li);
				}
				for(var i = startPageNo; i <= endPageNo; i++) {
					var li3 = d.createElement("li");
					var pageIndex=i;
					if(i == params.index) {
						li3.setAttribute("class", "active");
						pageIndex=0;
					}
					var a = "<a href='javascript:;' data-index='" + pageIndex + "'>" + i + "</a>";
					li3.innerHTML = a;
					li3.setAttribute("data-index", pageIndex);
					ul.appendChild(li3);
				}
				if(endPageNo!=pagecount){
					var li=d.createElement("li");
					var a = "<a href='javascript:;'  class='disabled' data-index='0'>…</a>";
					li.setAttribute("data-index", 0);
					li.innerHTML=a;
					ul.appendChild(li);
				}
				
				var li4 = d.createElement("li");
				var a = "<a href='javascript:;' data-index='" + (params.index + 1) + "'>下一页</a>";
				li4.innerHTML = a;
				li4.setAttribute("data-index", params.index == pagecount?0:(params.index + 1));
				ul.appendChild(li4);

				var li5 = d.createElement("li");
				var a = "<a href='javascript:;' data-index='" + pagecount + "'>末页</a>";
				li5.innerHTML = a;
				li5.setAttribute("data-index", params.index == pagecount?0:pagecount);
				ul.appendChild(li5);
				
				for(var i = 0; i < ul.childElementCount; i++) {
					(function() {
						var index = ul.children[i].getAttribute("data-index");
						if(index!="0"){
							coreui.on(ul.children[i], "click", function() {
								params.onpaging(index);
							});
						}else{
							//ul.children[i].addClass("disabled");
						}
					})();
				}
				pagecontainer.appendChild(ul);

				//是否开启跳页
				if(params.jump) {
					var jumpDiv = d.createElement('div');
					jumpDiv.setAttribute("class", "page-jump");
					var jumpHtml = "跳转到";
					jumpHtml += "<input id='jumpNo' type='number' min='1' max='" + pagecount + "'/>";
					jumpHtml += "页";
					jumpHtml += "<button type='button'>跳页</button>";
					jumpDiv.innerHTML = jumpHtml;
					coreui.on(jumpDiv.children[1], 'click', function() {
						if(jumpDiv.children[0].value <= pagecount && jumpDiv.children[0].value > 0 &&
							jumpDiv.children[0].value != params.index) {
							params.onpaging(jumpDiv.children[0].value);
						}
					});
					pagecontainer.appendChild(jumpDiv);
				}
				pager.innerHTML = "";
				pager.appendChild(pagecontainer);
			}else{
				pager.innerHTML = "没有数据";
			}
		},
		/*绑定事件*/
		on: function(obj, event, callback) {
			if(obj.addEventListener) {
				obj.addEventListener(event, callback);
			} else if(obj.attachEvent) {
				obj.attachEvent("on" + event, callback);
			}
		},
		/*导航插件*/
		nav: function(params) {

		},
		/*banner插件*/
		banner: function(params) {

		},
		/*广告插件*/
		ad: {
			/*漂浮广告*/
			float: function(params) {
				var winHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) - 15;
				var winWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth - 15);
				var width, height;
				var interval;
				var pattern;
				var floatStatus = 1; //正常状态
				if(params.img && params.content) {
					pattern = "img_text"; //图片&文字模式
					width = 200;
					height = 100;
				} else if(params.img) {
					pattern = "img"; //图片模式
				} else {
					pattern = "text"; //文字模式
					width = 200;
					height = 100;
				}
				//若调用时指定了宽高，则用调用时指定的
				if(params.width) {
					width = params.width;
				}
				if(params.height) {
					height = params.height;
				}
				//关闭图标或文字或图片，若都有则显示文字
				var closeText, closeIcon, closeImg;
				if(params.closeText) {
					closeText = params.closeText;
				} else if(params.closeIcon) {
					closeIcon = params.closeIcon;
				} else {
					closeImg = params.closeImg;
				}
				var XPos = getRandomNum(50, 300);
				var YPos = getRandomNum(50, 300);
				startFloat();
				//生成漂浮广告主体html
				function floatHmtl(xPos, yPos) {
					var htmlContent = document.createElement("div");
					htmlContent.setAttribute("class", "floatAd");
					htmlContent.setAttribute("id", "floatAd");
					htmlContent.setAttribute("style", "z-index:2000;border:2px solid white;position:relative;left:" + xPos + "px;top:" + yPos + "px;max-width:" + width + "px;max-height:" + height + "px;");
					htmlContent.addEventListener("mouseover", function() {
						floatStatus = 2;
					});
					htmlContent.addEventListener("mouseout", function() {
						floatStatus = 1;
					});
					var closeDiv = document.createElement("div");
					closeDiv.setAttribute("id", "floatAdClose");
					closeDiv.setAttribute("style", "position:absolute;right:-2px;top:0px;z-index:3000;cursor:pointer;color:red;");
					closeDiv.addEventListener('click', function() {
						clearInterval(interval);
						htmlContent.style.display = "none";
					});
					if(!params.closeIcon && !params.closeImg && !params.closeText) {
						closeDiv.innerHTML = "关闭";
					} else if(params.closeText) {
						closeDiv.innerHTML = params.closeText;
					} else if(params.closeIcon) {
						closeDiv.innerHTML = "<i class='fa fa-close'></i>";
					} else if(params.closeImg) {
						closeDiv.innerHTML = "<img src='" + params.closeImg + "'/>";
					}
					htmlContent.appendChild(closeDiv);
					if(params.target) var target = params.target;
					else var target = "_blank";
					if(pattern == "img_text") {
						var contentDiv = document.createElement("div");
						contentDiv.setAttribute("style", "margin:15px;");
						contentDiv.innerHTML = params.content;
						htmlContent.appendChild(contentDiv);
					} else if(pattern == "img") {
						var contentDiv = document.createElement("div");
						contentDiv.setAttribute("style", "margin:15px;");
						contentDiv.innerHTML = "<a href='" + params.url + "' target='" + target + "'>" + "<img id='floatAdImg' src='/" + params.img + "'/>" + "</a>";
						htmlContent.appendChild(contentDiv);
					} else {
						var contentDiv = document.createElement("div");
						contentDiv.setAttribute("style", "margin:15px;");
						contentDiv.innerHTML = "<a style='text-decoration:none;' href='" + params.url + "' target='" + target + "'>" + params.content + "</a>";
						htmlContent.appendChild(contentDiv);
					}
					document.body.appendChild(htmlContent);
				}

				//生成随机数
				function getRandomNum(Min, Max) {
					var Range = Max - Min;
					var Rand = Math.random();
					return(Min + Math.round(Rand * Range));
				}

				//开始
				function startFloat() {
					var first = true;
					var xOffset, yOffset;
					var offset = 1;
					var direction = getRandomNum(1, 4);
					if(direction == 1) {
						xOffset = -offset;
						yOffset = -offset;
					} else if(direction == 2) {
						xOffset = offset;
						yOffset = -offset;
					} else if(direction == 3) {
						xOffset = offset;
						yOffset = offset;
					} else {
						xOffset = -offset;
						yOffset = offset;
					}
					interval = setInterval(function() {
						if(first) {
							floatHmtl(XPos, YPos);
							first = false;
							if(pattern == "img") {
								var img = document.getElementById("floatAdImg");
								if(width) img.width = width;
								else width = img.width || img.clientWidth || img.style.width || img.offsetWidth;
								if(height) img.height = height;
								else height = img.height || img.clientHeight || img.style.height || img.offsetHeight;
								alert(width);
							}
						}
						if(floatStatus == 1) {
							XPos = XPos + xOffset;
							YPos = YPos + yOffset;
							/*if (XPos <= 0 && YPos <= 0) {
							    XPos = YPos = 0;
							    xOffset = offset;
							    yOffset = offset;
							    direction = 3;
							}else if (YPos <= 0&&XPos+width>=winWidth) {
							    YPos = 0;
							    XPos = winWidth - width;
							    xOffset = -offset;
							    yOffset = offset;
							    direction = 4;
							} else if (XPos <= 0 && YPos + height == winHeight) {
							    YPos = winHeight-height;
							    XPos = 0;
							    xOffset = offset;
							    yOffset = -offset;
							    direction = 2;
							} else if (XPos + width >= winWidth && YPos + height >= winHeight) {
							    YPos = winHeight - height;
							    XPos = winWidth-width;
							    xOffset = -offset;
							    yOffset = -offset;
							    direction = 1;
							} else*/
							if(YPos <= 0) {
								if(direction == 2) {
									xOffset = offset;
									direction = 3;
								} else {
									xOffset = -offset;
									direction = 4;
								}
								yOffset = offset;
								YPos = 0;
							} else if(XPos <= 0) {
								if(direction == 4) {
									yOffset = offset;
									direction = 3;
								} else {
									yOffset = -offset;
									direction = 2;
								}
								xOffset = offset;
								XPos = 0;
							} else if(YPos + height >= winHeight) {
								if(direction == 4) {
									xOffset = -offset;
									direction = 1;
								} else {
									xOffset = offset;
									direction = 2;
								}
								yOffset = -offset;
								YPos = winHeight - height;
							} else if(XPos + width >= winHeight) {
								if(direction == 2) {
									yOffset = -offset;
									direction = 1;
								} else {
									yOffset = offset;
									direction = 4;
								}
								XPos = winWidth - width;
							}
							changeFloat(XPos, YPos);
						} else changeFloat(XPos, YPos);
					}, 30);
				}

				function changeFloat(xPos, yPos) {
					var obj = document.getElementById("floatAd");
					obj.style.left = xPos + "px";
					obj.style.top = yPos + "px";
					if(pattern == "img") {
						var img = document.getElementById("floatAdImg");
						if(width) img.width = width + "px";
						else obj.style.width = img.clientWidth + "px";
						if(height) img.height = height;
						else obj.style.height = img.clientHeight + "px";

					}
				}
			}
		},
		/*验证插件*/
		validate: function(params) {

		}
	};
})();